package com.yes.yll.servlet;

import com.yes.yll.JdbcUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(urlPatterns = "/yllsave")
@MultipartConfig(location = "E:\\upload",maxFileSize =100*1024*1024,maxRequestSize =104857600 )
public class GoodsSave extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*String name = req.getParameter("n");
        String price = req.getParameter("p");
        Part picture = req.getPart("i");
        String fileName = picture.getSubmittedFileName();
        String[] strings = fileName.split("\\.");
        String suffix = strings[1];
        String img = RandomStringUtils.randomAlphabetic(10) + "." + suffix;

        picture.write(img);

        String sql = "INSERT INTO goods(`name`,price,image)VALUES(?,?,?)";
        JdbcUtils.modify(sql,name,price,img);
        resp.sendRedirect("/yll/goods-list.jsp");
*/



        String name = req.getParameter("n");
        String price = req.getParameter("p");
        String id = req.getParameter("id");
        /*Part picture = req.getPart("i");
        String fileName = picture.getSubmittedFileName();
        String[] strings = fileName.split("\\.");
        String suffix = strings[1];
        String img = RandomStringUtils.randomAlphabetic(10) + "." + suffix;

        picture.write(img);*/

        if(id!=null && !"null".equals(id)){
            //存在id，更新
            String sql="UPDATE goods SET `name`=?,price=? WHERE id=?";
            JdbcUtils.modify(sql,name,price,id);
        }else{
            Part picture = req.getPart("i");
            String fileName = picture.getSubmittedFileName();
            String[] strings = fileName.split("\\.");
            String suffix = strings[1];
            String img = RandomStringUtils.randomAlphabetic(10) + "." + suffix;

            picture.write(img);
            // 不存在id 新增
            String sql = "INSERT INTO goods(`name`,price,image)VALUES(?,?,?)";
            JdbcUtils.modify(sql,name,price,img);
        }

        resp.sendRedirect("/yll/goods-list.jsp");
    }
    }

